package com.zjsru.oneDay202205;

import java.util.Arrays;

/**
 * @Author: likew
 * @Date: 2022/5/17
 * 验证外星语词典
 * 输入：words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
 * 输出：true
 * 解释：在该语言的字母表中，'h' 位于 'l' 之前，所以单词序列是按字典序排列的。
 *
 * 输入：words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
 * 输出：false
 * 解释：在该语言的字母表中，'d' 位于 'l' 之后，那么 words[0] > words[1]，因此单词序列不是按字典序排列的。
 *
 */
public class isAlienSorted {
    public boolean isAlienSorted(String[] words, String order) {
       int[] ord = new int[26];
        for (int i = 0; i < 26; i++) {
            ord[order.charAt(i) - 'a'] = i;
        }
        String[] clone = words.clone();
        Arrays.sort(clone,(a,b) ->{
            int n = a.length(), m = b.length();
            int i = 0,j = 0;
            while(i < n && j < m){
                int c1 = a.charAt(i) - 'a', c2 = b.charAt(j) - 'a';
                if(c1 != c2) return ord[c1] - ord[c2];
                i++; j++;
            }
            if(i < n) return 1;
            if(j < m) return -1;
            return 0;
        });
        int n = words.length;
        for (int i = 0; i < n; i++) {
            if(!clone[i].equals(words[i])) return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        isAlienSorted isAlienSorted = new isAlienSorted();
        String[] word = new String[]{"word","world","row"};
        String order = "worldabcefghijkmnpqstuvxyz";
        System.out.println(isAlienSorted.isAlienSorted(word, order));
    }
}
